package com.cll.prototype.gateway.filters;

import com.alibaba.fastjson.JSONObject;
import com.cll.prototype.gateway.service.CheckTokenService;
import com.cll.prototype.gateway.service.IRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

/**
 * 描述信息:
 * 注册接口的限流工具
 * @author CLL
 * @version 1.0
 * @date 2020/11/1 7:32
 */
@Slf4j
@Component
public class RegistryRateLimiterFilter implements GlobalFilter, Ordered {

    @Autowired
    private CheckTokenService checkTokenService;

    @Autowired
    private IRateLimiter guavaRateLimiter;

    /**
     * 获取注册验证码的API
     */
    private static final String CREATE_REGISTRY_CAPTCHA_PATH = "/captcha/auth_captcha/createRegisterCaptcha";

    /**
     * 指定过滤器的业务逻辑的编写
     * @param exchange  webFlix。封装了web请求/响应对象
     * @param chain 过滤器链
     * @return  执行结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        RequestPath path = request.getPath();
        PathContainer pathWithinApplication = path.pathWithinApplication();

        InetSocketAddress remoteAddress = request.getRemoteAddress();
        if (null == remoteAddress) {
            log.error("****** 为获取到远端请求的网卡信息，直接进行返回吧");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String responseData = "未获取到远端网卡信息，禁止访问";
            DataBuffer wrap = response.bufferFactory().wrap(responseData.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        String clientIp = remoteAddress.getHostString();
        log.info("===>>> 请求的客户端IP = {}", clientIp);

        if (null == guavaRateLimiter){
            log.error("****** 注入限流工具失败");
        } else {
            log.info("===>>> 注入限流工具成功");
            if (CREATE_REGISTRY_CAPTCHA_PATH.equals(pathWithinApplication.value())){
                boolean rateLimiterFlag = guavaRateLimiter.applyAcquire(clientIp, 1, 60);
                if (!rateLimiterFlag) {
                    log.error("****** 限流生效。当前请求已被限流");
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    String responseData = "分钟级限流生效。当前请求已被限流";
                    DataBuffer wrap = response.bufferFactory().wrap(responseData.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
            }
        }

        if (null == checkTokenService){
            log.error("****** 注入[checkTokenService]工具失败");
        } else {
            log.info("===>>> 注入[checkTokenService]工具成功");
        }

        // 正常请求，放行
        return chain.filter(exchange);
    }

    /**
     * 定义当前过滤器在过滤器链中的位置。order越小优先级又高，越先执行
     * @return  过滤器级别
     */
    @Override
    public int getOrder() {
        return 1;
    }
}